import json
import logging
import random

import math
import redis
import requests
# 获取所有商品信息
from flask import current_app

from shop.conf import APP_KEY, PID, MOBILE, PASSWORD, MIAO_APKEY, TB_NAME, redis_host, redis_port


def get_all_kind_goods(page, kind):
    if kind:

        if kind == 100:
            url = 'https://api.taokezhushou.com/api/v1/search'
            params = {
                "app_key": APP_KEY,
                'page': int(page),
                'sort': "two_hour_sale_num",
            }
        else:
            url = "https://api.taokezhushou.com/api/v1/search"
            params = {
                "app_key": APP_KEY,
                'page': int(page),
                "cate_id": kind,
            }
    else:
        url = 'https://api.taokezhushou.com/api/v1/all'
        params = {
            "app_key": APP_KEY,
            'page': int(page)
        }
    res = requests.get(url=url, params=params)
    res_text = res.text
    res_json = json.loads(res_text)
    # 获取总的商品数量
    total_num = res_json.get('total')
    # 获取总的商品信息，一页一百个
    goods_data = res_json.get('data')

    new_goods_data = []
    for one_goods in goods_data:
        one_goods_id = one_goods.get("goods_id")
        one_goods["item_url"] = "https://detail.tmall.com/item.htm?id=" + str(one_goods_id)
        new_goods_data.append(one_goods)
    return new_goods_data, total_num


# 获取分页的数字
def get_pages(total, curremt_page):
    tmp = {}
    page_size = 100
    # 总分页数
    max_page = math.ceil(total / page_size)
    logging.warning(max_page)
    if not max_page:
        tmp = {
            "page_list": [],
            "has_per": 0,
            "per_num": 0,
            "has_next": 0,
            "next_num": 0,
            "current_page": 0
        }
        return tmp
    all_page_list = [x + 1 for x in range(max_page)]
    curremt_page_index = all_page_list.index(curremt_page)
    # 获取分页列表
    if curremt_page in all_page_list[0:9]:
        page_list = all_page_list[0:9]
    elif curremt_page in all_page_list[-9:]:
        page_list = all_page_list[-9:]
    else:
        page_list = all_page_list[curremt_page_index - 4:curremt_page_index + 5]
    tmp['page_list'] = page_list
    # 获取下一页和上一页的相关信息
    if curremt_page == 1:
        tmp['has_per'] = 0
        tmp['per_num'] = 0
    else:
        tmp['has_per'] = 1
        tmp['per_num'] = curremt_page - 1
    if curremt_page == all_page_list[-1]:
        tmp['has_next'] = 0
        tmp['next_num'] = 0
    else:
        tmp['has_next'] = 1
        tmp['next_num'] = curremt_page + 1
    tmp['current_page'] = curremt_page
    return tmp


# 获取商品分类下的信息
def get_one_kind_goods(page, kind):
    url = 'https://api.taokezhushou.com/api/v1/search'
    params = {
        "app_key": APP_KEY,
        'page': int(page)
    }
    res = requests.get(url, params=params)
    res_text = res.text
    res_json = json.loads(res_text)
    # 获取总的商品数量
    total_num = res_json.get('total')
    # 获取总的商品信息，一页一百个
    goods_data = res_json.get('data')
    return goods_data, total_num


# 搜索商品
def util_search_goods(page, words, order):
    logging.warning("这是具体的搜索商品的方法：")
    logging.warning("这是order的值：%s" % order)
    url = 'https://api.taokezhushou.com/api/v1/search'
    if order == 1:
        params = {
            "app_key": APP_KEY,
            "q": words,
            "page": int(page),
            "sort": "price_asc"
        }
    elif order == 2:
        params = {
            "app_key": APP_KEY,
            "q": words,
            "page": int(page),
            "sort": "price_desc"
        }
    elif order == 3:
        params = {
            "app_key": APP_KEY,
            "q": words,
            "page": int(page),
            "sort": "sale_num"
        }
    else:
        params = {
            "app_key": APP_KEY,
            "q": words,
            "page": int(page)
        }
    logging.warning(params)
    res = requests.get(url, params=params)
    res_text = res.text
    res_json = json.loads(res_text)
    # 获取总的商品数量
    total_num = res_json.get('total')
    # 获取总的商品信息，一页一百个
    goods_data = res_json.get('data')
    return goods_data, total_num


# 进入商品详情
def util_goods_detail(goods_id):
    url = 'https://api.taokezhushou.com/api/v1/detail'
    params = {
        "app_key": APP_KEY,
        "goods_id": goods_id
    }
    res = requests.get(url, params=params)
    res_text = res.text
    res_json = json.loads(res_text)
    goods_data = res_json.get('data')
    return goods_data


# 获取登录后的session
def tk_session():
    session = requests.session()
    login_url = 'http://www.taokezhushou.com/login'
    login_data = {
        "mobile": MOBILE,
        "password": PASSWORD
    }
    login_res = session.post(login_url, data=login_data)
    logging.warning(login_res)
    logging.warning(MOBILE)
    logging.warning(PASSWORD)
    return session


# 获取淘客助手session
def get_tkzs_cookies():
    # 首先查询redis中是否存在
    r = redis.StrictRedis(host=redis_host, port=redis_port)
    cookies_dict_str = r.get("tkzs_cookies")
    if not cookies_dict_str:
        tkzs_session = tk_session()
        cookies_dict = tkzs_session.cookies.get_dict()
        cookies_dict_str = json.dumps(cookies_dict)
        r.setex("tkzs_cookies", 60, cookies_dict_str)
        return cookies_dict
    else:
        current_app.logger.warning(cookies_dict_str)
        current_app.logger.warning(type(cookies_dict_str))
        cookies_dict = json.loads(cookies_dict_str.decode())
        return cookies_dict


# 获取商品优惠券
def util_get_yhq(goods_id, coupon_id, short_title):
    cookies_dict = get_tkzs_cookies()
    url = 'http://www.taokezhushou.com/zhuanlian'
    data = {
        "goods_id": goods_id,
        "coupon_id": coupon_id,
        'text': short_title,
        'pid': PID,
        'resp': 'td'
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Mobile Safari/537.36",
    }
    res = requests.post(url=url, data=data, cookies=cookies_dict, headers=headers)
    # 错误处理
    res_dict = json.loads(res.text)
    logging.warning(res_dict)
    if res_dict.get('status') == 200:
        yhq_dict = res_dict.get('data')
        return yhq_dict
    else:
        return {}


# 获取推荐商品
def get_recommend_goods():
    url = "https://api.taokezhushou.com/api/v1/search"
    goods_cate_id_list = [1, 6, 7, 5]
    goods_data = []

    for one_cate_id in goods_cate_id_list:
        params = {
            "app_key": APP_KEY,
            "sort": "commission_rate_desc",
            "cate_id": one_cate_id
        }
        res = requests.get(url, params=params)
        res_text = res.text
        res_json = json.loads(res_text)
        one_cate_goods_list = res_json.get("data")

        new_goods_list = []
        for one_goods in one_cate_goods_list:
            one_goods_id = one_goods.get("goods_id")
            one_goods["item_url"] = "https://detail.tmall.com/item.htm?id=" + str(one_goods_id)
            new_goods_list.append(one_goods)

        if len(new_goods_list):
            goods_data = goods_data + new_goods_list[0:25]

    # 获取总的商品数量
    total_num = 100
    random.shuffle(goods_data)
    return goods_data, total_num


def search_goods_v2(search_word, order, istmall, page):
    '''
    v2版本搜索商品操作
    :return: goods
    '''
    url = "http://api.web.21ds.cn/taoke/getTkMaterialItem"
    param_url = {
        "apkey": MIAO_APKEY,
        "pid": PID,
        "tbname": TB_NAME,
        "keyword": search_word,
        "hascoupon": "true",
        'pageno': int(page),
        "pagesize": 100
    }
    '''
    1是按价格升序,2是按价格降序,3是按销量排序
    '''
    # 排序方式
    if order == 1:
        # 升序
        param_url["sort"] = "price_asc"
    elif order == 2:
        # 降序
        param_url["sort"] = 'price_des'
    elif order == 3:
        # 总销量
        param_url['sort'] = 'total_sales_des'

    # 是否是天猫
    if istmall == 1:
        param_url['istmall'] = 'true'

    print(param_url)
    res = requests.get(url=url, params=param_url)
    res_text = res.text
    res_json = json.loads(res_text)
    # 获取总的商品信息，一页一百个
    goods_data = res_json.get('data')
    # 遍历商品信息，获取需要的商品
    res = []
    if isinstance(goods_data, dict):
        res = None
    else:
        all_items_url_list = []
        for one_goods in goods_data:
            tmp = {}
            tmp["num_iid"] = one_goods.get("num_iid")  # 商品id
            tmp["pict_url"] = one_goods.get("pict_url")  # 图片地址
            tmp['short_title'] = one_goods.get('short_title')  # 商品短标题
            tmp['title'] = one_goods.get('title')  # 商品标题
            tmp['zk_final_price'] = one_goods.get('zk_final_price')  # 券后价
            tmp['youhuiquan'] = one_goods.get('youhuiquan')  # 优惠券价格
            tmp['coupon_id'] = one_goods.get('coupon_id')  # 优惠券id
            tmp['coupon_start_time'] = one_goods.get('coupon_start_time')  # 优惠券开始时间
            tmp['coupon_end_time'] = one_goods.get('coupon_end_time')  # 优惠券结束时间
            tmp['volume'] = one_goods.get('volume')  # 销量
            tmp["seller_id"] = one_goods.get("seller_id")  # 销售id
            tmp['item_url'] = one_goods.get('item_url')  # 商品url
            res.append(tmp)
            all_items_url_list.append(tmp['item_url'])
        # rdu = RedisUtil()
        # rdu.set_list(items_url_queue_redis_key,all_items_url_list)
    return res


class GoodsOperation:
    def __init__(self):
        self.get_tkl_goods_url = "http://api.web.21ds.cn/taoke/doItemHighCommissionPromotionLinkByTpwd"

    def get_tkl_goods(self, tkl_str):
        '''
        根据淘口令获取商品
        :param tkl_str:
        :return:
        '''
        param_url = {
            "apkey": MIAO_APKEY,
            "pid": PID,
            "tbname": TB_NAME,
            "tpwdcode": tkl_str,
            "tpwd": 1,
        }
        res = requests.get(self.get_tkl_goods_url, params=param_url)
        res_dict = res.json()
        return res_dict

    def format_tkl_goods_res(self, res):
        '''
        格式化淘口令商品信息
        :return:
        '''
        if res.get("code") != 200:
            return {}
        else:
            tmp = {}
            data = res.get("data")
            tmp["num_iid"] = data.get("item_info").get("num_iid")  # 商品id
            tmp["pict_url"] = data.get("item_info").get("pict_url")  # 图片地址
            tmp['short_title'] = data.get("item_info").get("title")  # 商品短标题
            tmp['title'] = data.get("item_info").get("title")  # 商品标题
            tmp['zk_final_price'] = data.get("item_info").get('zk_final_price')  # 券后价
            tmp['youhuiquan'] = data.get('youhuiquan')  # 优惠券价格
            tmp['coupon_id'] = data.get('item_id')  # 优惠券id
            tmp['coupon_start_time'] = data.get('coupon_start_time')  # 优惠券开始时间
            tmp['coupon_end_time'] = data.get('coupon_end_time')  # 优惠券结束时间
            tmp['volume'] = data.get("item_info").get('volume')  # 销量
            tmp["seller_id"] = data.get("item_info").get("seller_id")  # 销售id
            tmp['item_url'] = data.get("item_info").get('item_url')  # 商品url
            return tmp
